﻿using System;
using System.Collections.Generic;
using ZilLion.Core.Unities.UnitiesMethods;
using ZilLion.TPO2O.SDK.EntityBase;

namespace ZilLion.TPO2O.SDK
{

    /// <summary>
    /// token容器 线程安全
    /// </summary>
    public class TokenContainer
    {
        private readonly object _lockobj = new object();
        private JwtResponseResultInfo _currenttoken;


        public string TryGetToken()
        {
            if (_currenttoken != null && Math.Round(
                    (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
                    .TotalSeconds
                ).ToLongOrDefault() > _currenttoken.Exp) return _currenttoken.JwtToken;

            #region 生成Token临时代码  todo 从服务端获取
            var exp =
               Math.Round((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds +
                          60).ToInt32();
            var payload = new Dictionary<string, dynamic>
            {
                {"tpkey", "15952024960"}, //第三方Key
                {"exp", exp}, //过期时间（秒）
                {"requestApiVersion", "1.0.0.0"}, //请求的Api版本
                {"zilLionAppType", "Z9020"} //商周应用类型
            };
            var token = JwtTokenUtility.EncodeJwtToken(payload,
                "08e88575a79744e4bc75341fd234c126");

           

            #endregion

            lock (_lockobj)
            {
                _currenttoken = new JwtResponseResultInfo {Exp = exp, JwtToken = token};
            }
            return _currenttoken.JwtToken;
        }

        #region Singleton

        private static TokenContainer _instance;
        private static readonly object _instancelocker = new object();

        private TokenContainer()
        {
        }

        public static TokenContainer Instance()
        {
            //没有第一重 instance == null 的话，每一次有线程进入 GetInstance()时，均会执行锁定操作来实现线程同步，
            //非常耗费性能 增加第一重instance ==null 成立时的情况下执行一次锁定以实现线程同步
            if (_instance == null)
                lock (_instancelocker)
                {
                    //Double-Check Locking 双重检查锁定 
                    if (_instance == null) _instance = new TokenContainer();
                }
            return _instance;
        }

        #endregion
    }
}